package com.godme.concurrent.block;

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class Block {

    public static void main(String[] args) throws InterruptedException {
        Queue q = new Queue();
        new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                try {
                    if(i % 10 == 0){
                        Thread.sleep(1000);
                        System.err.println("==================");
                    }
                    q.put(i);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
        new Thread(() -> {
            while (true){
                try {
                    System.err.println(q.get());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
        new Thread(()->{
            BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
            String line ;
            try{
                while((line = reader.readLine()) != null){
                    q.put(Integer.parseInt(line));
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }).start();
    }


    static class Queue{

        int a = -1;
        boolean readable = false;
        public  synchronized void put(int a) throws InterruptedException {
            if(readable){
                wait();
            }
            readable = true;
            this.a = a;
            notify();
        }

        public synchronized int get() throws InterruptedException {
            if(!readable){
                wait();
            }
            notify();
            readable = false;
            return this.a;
        }
    }


}
